package org.demo.base.jdbc;

import com.mysql.jdbc.Driver;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * rollback() 的作用释放锁，清除这个连接原来执行的sql,如果连接没有关闭，不会滚，下次commit会把未提交的执行了
 *
 * 使用数据库连接池获取连接，在使用时需要手动关闭链接，实际上并没有关闭链接，只是将链接释放放会数据库连接池中
 *
 *
 */
public class TestTransactionRollback {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        String sql = "UPDATE account SET money = ? WHERE name = ?";
        try {
            DriverManager.registerDriver(new Driver());
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/zhaofei", "root", "root");
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,900);
            preparedStatement.setString(2,"aaa");
            preparedStatement.addBatch();
            preparedStatement.setInt(1,700);
            preparedStatement.setString(2,"aaaa");
            preparedStatement.addBatch();
            preparedStatement.setInt(1,600);
            preparedStatement.setString(2,"bbbb");
            preparedStatement.addBatch();
            int[] ints = preparedStatement.executeBatch();
            System.out.println(Arrays.toString(ints));
            boolean execute = preparedStatement.execute("UPDATE account SET money = 100 WHERE names = '22'");
            System.out.println(execute);
            connection.commit();

        }catch (SQLException e){
            e.printStackTrace();
            try {
//                connection.rollback();
                boolean execute = preparedStatement.execute("UPDATE account SET money = 100 WHERE name = '22'");
                System.out.println(execute);
                connection.commit();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }


        }finally {
//            try {
//                if(preparedStatement!=null){
//                    preparedStatement.close();
//                }
//                if(connection!=null){
//                    connection.close();
//                }
//            }catch (SQLException e){
//                e.printStackTrace();
//            }


        }
    }
}
